<template>
  <div class="app-container">
    <div display="block">
      <div align="right">
        <Icon name="add-o" style="right: 10px;" @click="onAdd"></Icon>
      </div>
    </div>
    <div v-if="!dataRecordTable||dataRecordTable.length===0" align="center">暂无数据</div>
    <List v-for="item of dataRecordTable">
      <SwipeCell :key="item.value.id">
        <template #left>
          <Button square type="primary" text="选择"/>
        </template>
        <cell :title="item.value.display_name" is-link :to="'/Form/'+model+'/'+item.value.id"/>
        <template #right>
          <Button square type="danger" text="删除" @click="deleteRow(item)"/>
          <Button square type="primary" text="编辑" :to="'/EditForm/'+model+'/'+item.value.id"/>
        </template>
      </SwipeCell>
    </List>
    <div style="font-size: 5px;position: absolute;bottom:0px;right:0px">Table</div>
  </div>

</template>

<script>
  // import Vue from 'vue'
  import {Button, Cell, CellGroup, Dialog, Icon, List, SwipeCell} from "vant"
  import field from '../Field'
  import {msgField, ratingField, table, websiteField} from '../api/http'
  import gql from 'graphql-tag'
  // Vue.use(Dialog)
  export default {
    name: 'Table',
    components: {field, Cell, CellGroup, List, SwipeCell, Button, Icon},
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'info',
          deleted: 'danger'
        }
        return statusMap[status]
      }
    },
    data() {
      return {
        datas: {},
        dataField: null,
        queryFields: null,
        dataRecordTable: null,
        info: 0,
        searchName: '',
        timeInterval: null,
        model: '',
        loading: false,
        list: null,
        total: 0,
        listQuery: {
          page: 1,
          limit: 20
        },
        multipleSelection: [],
        delVisible: false,
        order: '__last_update desc',
        tablePage: {
          currentPage: 1,
          pageSize: 25
        },
        response: {},
        result: {},
        record: {},
        groupRecord: [],
        groupby: [],
        groupResult: [],
        fields: {},
        canUnlink: false,
        todelid: 0,// 删除使用的临时变量
        toolbar: {
          custom: true,
          zoom: true,
          refresh: {query: this.reload},
          buttons: [{name: '新增', code: 'newRecord', visible: true, icon: 'fa fa-plus'}, {
            name: '导出',
            code: 'exportDataEvent',
            visible: true,
            icon: 'fa fa-export'
          }],
          slots: {buttons: 'toolbar_buttons'}
        }
      }
    },
    apollo: {
      jfields: {
        query: gql`query qdv($model:String){
          jfields:allJfield(model:$model)
          }`,
        variables() {
          return {
            model: this.model
          }
        },
        skip() {
          return !this.model
        }
      },
      dataField: {
        query: gql`query qdv($domain:String){
          dataField:allMobileModel(domain:$domain) {
              fieldsListIds{
                name
                id
                fieldDescription
                help
                type:ttype
              }
            }
          }`,
        variables() {
          return {
            domain: JSON.stringify([['model', '=', this.model]])
          }
        },
        skip() {
          return !this.model
        }

      },
      dataRecordTable: {
        query: gql`query qdv($model:String,$domain:String!,$queryFields:[String],$order:String,$limit:Int,$offset:Int){
                   dataRecordTable:allRecord(model:$model,domain:$domain,fields:$queryFields,order:$order,limit:$limit,offset:$offset){
            value
          }
          count:count(model:$model,domain:$domain)
         }`,
        variables() {
          return {
            model: this.model,
            queryFields: this.queryFields,
            offset: ((this.tablePage.currentPage - 1) * this.tablePage.pageSize) || 0,
            domain: JSON.stringify(this.domain),
            order: this.order,
            limit: this.tablePage.pageSize
          }
        },
        skip() {
          return !(this.model && this.queryFields)
        }
      },
      info: {
        query: gql`query qdv($model:String){
                   info:info(model:$model)
         }`,
        variables() {
          return {
            model: this.model,
          }
        },
        skip() {
          return !(this.model)
        }
      },
    },
    computed: {
      domain: function () {
        let d = []
        if (this.$refs.filter) d = this.$refs.filter.domain
        if (this.searchName && this.searchName.length > 0) {
          let v = []
          v.push(['name', 'ilike', this.searchName])
          v.concat(d)
          return v
        } else return d
      }
    },

    watch: {
      $route(to, from) {
        // 刷新参数放到这里里面去触发就可以刷新相同界面了
        if (to.name === 'Table') {
          this.model = to.params.model
          this.offset = 0
          this.record = []
          this.groupby = []
          this.$apollo.queries.dataRecordTable.refetch()
        }
      },
      'groupby'(to, from) {
        let groupby = to
        if ((groupby.length > 0) && (groupby !== from)) {

        }
      },
      dataField: function (to, from) {
        this.refersh()
      },
      jfields(to, from) {
        this.refersh()
      }, info(to, from) {
        //修改导航栏标题
        this.$emit('onTitle', to.name)
      }
    },
    mounted: function () {
      this.model = this.$route.params.model
      let self = this
      self.offset = 0
    },
    methods: {
      refersh() {
        if (this.dataField && this.jfields) {
          let val = []
          let other = []
          let dfields = (this.dataField[0] && this.dataField[0].fieldsListIds) ? this.dataField[0].fieldsListIds.map(x => x.name) : []
          for (let item of Object.keys(this.jfields)) {
            if (websiteField.indexOf(item) >= 0) {
              this.website = true
              // } else if (baseField.indexOf(item) >= 0) {
              // this.website = true
            } else if (ratingField.indexOf(item) >= 0) {
              this.rating = true
            } else if (msgField.indexOf(item) >= 0) {
              this.mail = true
            } else if (dfields.indexOf(item) >= 0 || item.name === 'id' || item.name === 'display_name') {
              val.push(item)
            } else {
              let v = {}
              v[item] = this.jfields[item]
              other.push(v)
            }
          }
          this.queryFields = val
          this.otherFields = other
        }
      },
      reload() {
        this.$apollo.queries.dataRecordTable.refetch()
      },
      refetch() {
        this.$apollo.queries.dataField.refetch()
        this.$apollo.queries.dataRecordTable.refetch()
      },
      switchData(id) {
        let data = this.datas[id]
        if (!data) {
          data = {
            timeInterval: null,
            model: id,
            loading: false,
            list: null,
            total: 0,
            listQuery: {
              page: 1,
              limit: 20
            },
            multipleSelection: [],
            delVisible: false,
            order: '__last_update desc',
            tablePage: {
              currentPage: 1,
              pageSize: 25
            },
            response: {},
            result: {},
            record: {},
            groupRecord: [],
            domain: [],
            groupby: [],
            groupResult: [],
            fields: {},
            canUnlink: false,
            todelid: 0 // 删除使用的临时变量
          }
          this.datas[id] = data
        }
        this.data = data
      },
      sortChange: function (column, property, order) {
        // console.debug(column, property, order)
        switch (column.order) {
          case 'asc':
            this.order = column.prop + ' asc'
            break
          case 'desc':
            this.order = column.prop + ' desc'
            break
          default:
            this.order = ''
        }
      },
      fmkdata: function (record) {
        let val = []
        for (let i in record) {
          let value = record[i]
          value['treeNode'] = false
          val.push(value)
        }
        return val
      },
      fmkGroup: function (self, record) {
        let val = []
        for (let i = 0; i < record.length; i++) {
          let item = record[i]
          val.push({
            treeNode: true,
            name: item[self.groupby[0]][1],
            count: item[self.groupby[0] + '_count'],
            children: [],
            hasChild: true,
            domain: item['__domain']
          })
        }
        return val
      },
      handlePageChange({currentPage, pageSize}) {
        this.tablePage.currentPage = currentPage
        this.tablePage.pageSize = pageSize
      },
      loadChildrenMethod({row}) {
        // 异步加载子节点
        // console.info(row)
        let self = this

        return new Promise(resolve => {
          table(self.model, {
            domain: row.domain,
            order: self.order,
            limit: self.tablePage.pageSize,
            offset: ((self.tablePage.currentPage - 1) * self.tablePage.pageSize) || 0
          }).then(function (response) {
            if (!response) {
              return
            }
            let result = response.result
            // self.tablePage.totalResult = self.result.count
            let record = result.record

            row.children = self.fmkdata(record)
            self.loading = false
            clearInterval(self.timeInterval)
            resolve(row.children)
          }, function (error) {
            console.error(error)
            self.loading = false
            clearInterval(self.timeInterval)
          })
        })
      },
      toolbarButtonClickEvent({code}, event) {
        switch (code) {
          case 'newRecord':
            this.newRecord(code)
            break
          case 'exportDataEvent':
            this.exportDataEvent(code)
            break
        }
      },
      onAdd() {
        this.$router.push({
          name: 'pagenewform',
          query: {
            model: this.model,
            id: 0,
          }
        })

        this.listLoading = false
      },
      doedit: function (index, item) {
        this.$router.push({
          name: 'EditForm',
          params: {model: this.app_root.model, active_id: item.id.value, name: item.display_name.value}
        })
      },
      handleDelete: function (index, item) {
        this.todelid = item.value.id
        this.delVisible = true
      }, // 确定删除
      deleteRow(item) {
        let self = this
        console.info(item)
        Dialog.confirm({
          title: '删除记录',
          message: `确认删除${item.value.display_name}?`,
        })
          .then(() => {
            this.$apollo.mutate({
              mutation: gql`mutation($model:String!,$id:Int!){
              unlinkRecord(model:$model,id:$id){
                ok
              }
            }`,
              variables: {model: self.model, id: item.value.id}
            }).then(
              function () {
                // self.$message.success('删除成功')
                self.delVisible = false
                self.reload()
              },
              function () {
              }
            )
          })
          .catch(() => {
            // on cancel
          });
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
        if (this.multipleSelection.length > 0) this.canUnlink = right.unlink
        else this.canUnlink = false
      },
    }
  }
</script>

<style scoped>
  .edit-input {
    padding-right: 100px;
  }

  .cancel-btn {
    position: absolute;
    right: 15px;
    top: 10px;
  }
</style>
